<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class User extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('user')
            ->addOption('sync', null, Option::VALUE_REQUIRED, 'sync work wechat user')
            ->setDescription('the user command');        
    }

    protected function execute(Input $input, Output $output)
    {
    	// 指令输出
    	$output->writeln('user');
        $sync = $input->getOption('sync');
        switch ($sync) {
            case 'work_wechat':
                $this->syscWorkWechatUser();
                break;
            default:
                break;
        }
    }

    protected function syscWorkWechatUser()
    {
        $configLogic = new \app\common\config\logic\ConfigSystem();
        $config = $configLogic->getConfigItem('work_wechat');
        $admin = $config['admin'];

        $userLogic = new \app\common\system\logic\UserLogic();
        $wechatLogic = new \app\common\third\Wechat();
        // 获取所有未同步的员工
        $userModel = new \app\common\system\model\User();
        $users = $userModel->where('status', 1)->where('is_sync_work_wechat', 1)->where('work_wechat', '')->select();
        
        $notMatches = [];
        foreach ($users as $user) {
            $result = $wechatLogic->get_user_id($user['mobile']);
            print_r($result);
            if ($result['errcode'] == 0) {
                $user->save(['work_wechat' => $result['userid']]);
                // 重置用户的缓存
                $userLogic->resetUserCache($user['id']);
            } else {
                $notMatches[] = $user['realname'];    
            }
        }

        if (!empty($notMatches)) {
            $content = "员工".implode(',', $notMatches)."的手机号未匹配到企业微信，请在员工管理中手动绑定或者取消同步";
            $wechatLogic->send_text_message($admin, $content);
        }
    }
}
